import json
from typing import Dict, Any, List, Optional

from openai import OpenAI
from openai.types.chat.chat_completion import Choice


class SinaFinanceNewsSearcher:  
    def __init__(self, api_key: Optional[str] = None):  
        """  
        初始化 SinaFinanceNewsSearcher  
        """  
        self.client = OpenAI(  
            base_url="https://api.moonshot.cn/v1",  
            api_key="sk-tpn91788BizFBRHbkg111111" 
        )  
        
        self.initial_messages = [  
            {  
                "role": "system",   
                "content": """你是一个金融工作者，现在要收集每天相关的金融信息，你从财经新闻网站获取数据。
请按照以下JSON格式返回数据：
{
  "news_list": [
    {
      "title": "新闻标题",
      "content": "新闻内容摘要，不超过200字",
      "source": "新闻来源",
      "time": "新闻时间，格式为YYYY-MM-DD HH:MM",
      "url": "新闻链接"
    }
  ]
}

请确保返回的是有效的JSON格式，并且包含至少3条最新、最重要的财经新闻。新闻应该按重要性排序，最重要的在前面。"""
            }  
        ]

    def _search_impl(self, arguments: Dict[str, Any]) -> Any:  
        """  
        搜索实现，目前直接返回参数  
        
        :param arguments: 搜索参数  
        :return: 搜索结果  
        """  
        return arguments  

    def search_finance_news(self, query: Optional[str] = None) -> str:  
        """  
        搜索金融新闻  

        :param query: 可选的搜索查询，默认为今天的热点新闻  
        :return: 搜索结果内容  
        """  
        messages = self.initial_messages.copy()  
        
        # 如果没有提供查询，使用默认查询  
        if query is None:  
            query = "搜索今天有什么热点财经新闻，并按照要求的JSON格式返回"  
        
        messages.append({  
            "role": "user",  
            "content": query  
        })  

        finish_reason = None  
        while finish_reason is None or finish_reason == "tool_calls":  
            choice = self._chat(messages)  
            finish_reason = choice.finish_reason  
            
            if finish_reason == "tool_calls":  
                messages.append(choice.message)  
                
                for tool_call in choice.message.tool_calls:  
                    tool_call_name = tool_call.function.name  
                    tool_call_arguments = json.loads(tool_call.function.arguments)  
                    
                    if tool_call_name == "$web_search":  
                        tool_result = self._search_impl(tool_call_arguments)  
                    else:  
                        tool_result = f"Error: unable to find tool by name '{tool_call_name}'"  

                    messages.append({  
                        "role": "tool",  
                        "tool_call_id": tool_call.id,  
                        "name": tool_call_name,  
                        "content": json.dumps(tool_result)  
                    })  

        return choice.message.content  

    def _chat(self, messages: List[Dict[str, str]]) -> Choice:  
        """  
        调用 Moonshot AI 聊天接口  

        :param messages: 消息列表  
        :return: 聊天返回结果  
        """  
        completion = self.client.chat.completions.create(  
            model="moonshot-v1-128k-vision-preview",  
            messages=messages,  
            temperature=0.3,  
            tools=[  
                {  
                    "type": "builtin_function",  
                    "function": {  
                        "name": "$web_search",  
                    }  
                }  
            ]  
        )  
        return completion.choices[0]  


# def refresh_kimi_token():
#     """
#     刷新Kimi API密钥
#     在密钥被更新后调用此函数以确保使用最新的密钥
#     """
#     global kimi_api_key

#     # 使用工具函数获取最新的密钥
#     new_key = read_file_with_fallback(local_file_path, FormItemsKey.KIMI_TOKEN)

#     if new_key and new_key != kimi_api_key:
#         kimi_api_key = new_key
#         AntLogger.info("已刷新Kimi API密钥")

#     return kimi_api_key


def get_sina_finance_news(api_key: Optional[str] = None, query: Optional[str] = None) -> str:  
    """  
    外部调用函数，获取新浪财经新闻  

    :param api_key: 可选的 Moonshot AI 的 API Key  
    :param query: 可选的搜索查询  
    :return: 新闻内容  
    """  
    searcher = SinaFinanceNewsSearcher(api_key)  
    return searcher.search_finance_news(query)  

# # 使用示例  
# if __name__ == "__main__":  
#     # 使用全局配置的API密钥
#     news = get_sina_finance_news("sk-tpn917881111126b")
#     print(news)